package com.xuetang.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private JwtTokenUtil jwtTokenUtil;

    // 不需要验证的路径
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/admin/login",
            "/api/articles",
            "/static",
            "/favicon.ico");

    public JwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 检查请求路径是否需要跳过验证
        String path = request.getRequestURI();
        boolean shouldSkip = EXCLUDE_PATHS.stream().anyMatch(path::startsWith);

        // 处理OPTIONS请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        if (shouldSkip) {
            // 不需要验证的路径，直接放行
            chain.doFilter(request, response);
            return;
        }

        // 从HTTP请求头中取出token
        String authHeader = request.getHeader(jwtTokenUtil.getHeader());

        // 对于API请求，如果没有token，返回401
        if (path.startsWith("/admin")
                && (authHeader == null || !authHeader.startsWith(jwtTokenUtil.getTokenPrefix()))) {
            // 对于API请求，设置响应头允许跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            response.setHeader("Access-Control-Max-Age", "3600");

            // 返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未授权\",\"data\":null}");
            return;
        }

        // 继续过滤器链
        chain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();

        // 对于OPTIONS请求，不进行过滤
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        return EXCLUDE_PATHS.stream().anyMatch(path::startsWith);
    }
}